package com.laboratory.io;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileInputStreamTest
{
	public static void main(String[] args) throws IOException
	{
	//	firstMethod();
//		secondMethod();
//		thirdMethod();
		fourthMethod();
	}

	public static void  firstMethod() throws  IOException{
		//创建字节输入流
		FileInputStream fis = new FileInputStream("src/IO/FileInputStreamTest.java");
		//创建一个长度为1024的“竹筒”
		byte[] bbuf = new byte[32];
		//用于保存实际读取的字节数
		int hasRead = 0;
		//使用循环来重复“取水”过程
		while ((hasRead = fis.read(bbuf)) > 0 )
		{
			//取出“竹筒”中水滴（字节），将字节数组转换成字符串输入！
			System.out.print(new String(bbuf , 0 , hasRead ));
		}
		fis.close();
	}
	
	public static void secondMethod() throws  IOException{
		// create new file input stream
		FileInputStream fis = new FileInputStream("/Users/ch/IdeaProjects/util/src/main/java/com/laboratory/io/newFile.txt");
        // skip bytes from file input stream
		Long l= fis.skip(0);
		System.out.println(l);
        // read bytes from this stream
       int i = fis.read();
       System.out.println(i);
        // converts integer to character
       char c = (char)i;
       System.out.println("char:"+i);
		
	}
	public static void thirdMethod() throws  IOException{
		byte[] bytes = "ABCDEF".getBytes();
		try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
			for (int i = 0; i < 9; i++) {
				if(i == 2){
					in.mark(1);
				}
				System.out.println(in.read());

				if(i==4){
					in.reset();
				}
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}

	public static void fourthMethod() throws  IOException{
		byte[] bytes = "ABCDEFCD".getBytes();
		byte[] subBytes = "CD".getBytes();
		try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
			for (int i = 0; i < 9; i++) {
				if(i>0 && i%2 == 0){
					in.skip(subBytes.length);
 				}
				System.out.println(new String(new byte[]{(byte)in.read()}));
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
}
